{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Approximate q-learning\n",
    "\n",
    "In this notebook you will teach a __pytorch__ neural network to do Q-learning."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # in google colab uncomment this\n",
    "\n",
    "# import os\n",
    "\n",
    "# os.system('apt-get install -y xvfb')\n",
    "# os.system('wget https://raw.githubusercontent.com/yandexdataschool/Practical_DL/fall18/xvfb -O ../xvfb')\n",
    "# os.system('apt-get install -y python-opengl ffmpeg')\n",
    "# os.system('pip install pyglet==1.2.4')\n",
    "\n",
    "# XVFB will be launched if you run on a server\n",
    "import os\n",
    "if type(os.environ.get(\"DISPLAY\")) is not str or len(os.environ.get(\"DISPLAY\")) == 0:\n",
    "    !bash ../xvfb start\n",
    "    os.environ['DISPLAY'] = ':1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import gym\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "env = gym.make(\"CartPole-v0\").env\n",
    "env.reset()\n",
    "n_actions = env.action_space.n\n",
    "state_dim = env.observation_space.shape\n",
    "\n",
    "plt.imshow(env.render(\"rgb_array\"))\n",
    "env.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Approximate Q-learning: building the network\n",
    "\n",
    "To train a neural network policy one must have a neural network policy. Let's build it.\n",
    "\n",
    "\n",
    "Since we're working with a pre-extracted features (cart positions, angles and velocities), we don't need a complicated network yet. In fact, let's build something like this for starters:\n",
    "\n",
    "![img](https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/yet_another_week/_resource/qlearning_scheme.png)\n",
    "\n",
    "For your first run, please only use linear layers (nn.Linear) and activations. Stuff like batch normalization or dropout may ruin everything if used haphazardly. \n",
    "\n",
    "Also please avoid using nonlinearities like sigmoid & tanh: agent's observations are not normalized so sigmoids may become saturated from init.\n",
    "\n",
    "Ideally you should start small with maybe 1-2 hidden layers with < 200 neurons and then increase network size if agent doesn't beat the target score."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "network = nn.Sequential()\n",
    "\n",
    "network.add_module('layer1', < ... >)\n",
    "\n",
    "<YOUR CODE: stack layers!!!1 >\n",
    "\n",
    "# hint: use state_dim[0] as input size"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_action(state, epsilon=0):\n",
    "    \"\"\"\n",
    "    sample actions with epsilon-greedy policy\n",
    "    recap: with p = epsilon pick random action, else pick action with highest Q(s,a)\n",
    "    \"\"\"\n",
    "    state = torch.tensor(state[None], dtype=torch.float32)\n",
    "    q_values = network(state).detach().numpy()\n",
    "\n",
    "    # YOUR CODE\n",
    "\n",
    "    return int( < epsilon-greedily selected action > )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s = env.reset()\n",
    "assert tuple(network(torch.tensor([s]*3, dtype=torch.float32)).size()) == (\n",
    "    3, n_actions), \"please make sure your model maps state s -> [Q(s,a0), ..., Q(s, a_last)]\"\n",
    "assert isinstance(list(network.modules(\n",
    "))[-1], nn.Linear), \"please make sure you predict q-values without nonlinearity (ignore if you know what you're doing)\"\n",
    "assert isinstance(get_action(\n",
    "    s), int), \"get_action(s) must return int, not %s. try int(action)\" % (type(get_action(s)))\n",
    "\n",
    "# test epsilon-greedy exploration\n",
    "for eps in [0., 0.1, 0.5, 1.0]:\n",
    "    state_frequencies = np.bincount(\n",
    "        [get_action(s, epsilon=eps) for i in range(10000)], minlength=n_actions)\n",
    "    best_action = state_frequencies.argmax()\n",
    "    assert abs(state_frequencies[best_action] -\n",
    "               10000 * (1 - eps + eps / n_actions)) < 200\n",
    "    for other_action in range(n_actions):\n",
    "        if other_action != best_action:\n",
    "            assert abs(state_frequencies[other_action] -\n",
    "                       10000 * (eps / n_actions)) < 200\n",
    "    print('e=%.1f tests passed' % eps)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Q-learning via gradient descent\n",
    "\n",
    "We shall now train our agent's Q-function by minimizing the TD loss:\n",
    "$$ L = { 1 \\over N} \\sum_i (Q_{\\theta}(s,a) - [r(s,a) + \\gamma \\cdot max_{a'} Q_{-}(s', a')]) ^2 $$\n",
    "\n",
    "\n",
    "Where\n",
    "* $s, a, r, s'$ are current state, action, reward and next state respectively\n",
    "* $\\gamma$ is a discount factor defined two cells above.\n",
    "\n",
    "The tricky part is with  $Q_{-}(s',a')$. From an engineering standpoint, it's the same as $Q_{\\theta}$ - the output of your neural network policy. However, when doing gradient descent, __we won't propagate gradients through it__ to make training more stable (see lectures).\n",
    "\n",
    "To do so, we shall use `x.detach()` function which basically says \"consider this thing constant when doingbackprop\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def to_one_hot(y_tensor, n_dims=None):\n",
    "    \"\"\" helper: take an integer vector and convert it to 1-hot matrix. \"\"\"\n",
    "    y_tensor = y_tensor.type(torch.LongTensor).view(-1, 1)\n",
    "    n_dims = n_dims if n_dims is not None else int(torch.max(y_tensor)) + 1\n",
    "    y_one_hot = torch.zeros(\n",
    "        y_tensor.size()[0], n_dims).scatter_(1, y_tensor, 1)\n",
    "    return y_one_hot\n",
    "\n",
    "\n",
    "def where(cond, x_1, x_2):\n",
    "    \"\"\" helper: like np.where but in pytorch. \"\"\"\n",
    "    return (cond * x_1) + ((1-cond) * x_2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def compute_td_loss(states, actions, rewards, next_states, is_done, gamma=0.99, check_shapes=False):\n",
    "    \"\"\" Compute td loss using torch operations only. Use the formula above. \"\"\"\n",
    "    states = torch.tensor(\n",
    "        states, dtype=torch.float32)    # shape: [batch_size, state_size]\n",
    "    actions = torch.tensor(actions, dtype=torch.int32)    # shape: [batch_size]\n",
    "    rewards = torch.tensor(rewards, dtype=torch.float32)  # shape: [batch_size]\n",
    "    # shape: [batch_size, state_size]\n",
    "    next_states = torch.tensor(next_states, dtype=torch.float32)\n",
    "    is_done = torch.tensor(is_done, dtype=torch.float32)  # shape: [batch_size]\n",
    "\n",
    "    # get q-values for all actions in current states\n",
    "    predicted_qvalues = network(states)\n",
    "\n",
    "    # select q-values for chosen actions\n",
    "    predicted_qvalues_for_actions = torch.sum(\n",
    "        predicted_qvalues * to_one_hot(actions, n_actions), dim=1)\n",
    "\n",
    "    # compute q-values for all actions in next states\n",
    "    predicted_next_qvalues =  # YOUR CODE\n",
    "\n",
    "    # compute V*(next_states) using predicted next q-values\n",
    "    next_state_values =  # YOUR CODE\n",
    "    assert next_state_values.dtype == torch.float32\n",
    "\n",
    "    # compute \"target q-values\" for loss - it's what's inside square parentheses in the above formula.\n",
    "    target_qvalues_for_actions =  # YOUR CODE\n",
    "\n",
    "    # at the last state we shall use simplified formula: Q(s,a) = r(s,a) since s' doesn't exist\n",
    "    target_qvalues_for_actions = where(\n",
    "        is_done, rewards, target_qvalues_for_actions)\n",
    "\n",
    "    # mean squared error loss to minimize\n",
    "    loss = torch.mean((predicted_qvalues_for_actions -\n",
    "                       target_qvalues_for_actions.detach()) ** 2)\n",
    "\n",
    "    if check_shapes:\n",
    "        assert predicted_next_qvalues.data.dim(\n",
    "        ) == 2, \"make sure you predicted q-values for all actions in next state\"\n",
    "        assert next_state_values.data.dim(\n",
    "        ) == 1, \"make sure you computed V(s') as maximum over just the actions axis and not all axes\"\n",
    "        assert target_qvalues_for_actions.data.dim(\n",
    "        ) == 1, \"there's something wrong with target q-values, they must be a vector\"\n",
    "\n",
    "    return loss"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# sanity checks\n",
    "s = env.reset()\n",
    "a = env.action_space.sample()\n",
    "next_s, r, done, _ = env.step(a)\n",
    "loss = compute_td_loss([s], [a], [r], [next_s], [done], check_shapes=True)\n",
    "loss.backward()\n",
    "\n",
    "assert len(loss.size()) == 0, \"you must return scalar loss - mean over batch\"\n",
    "assert np.any(next(network.parameters()).grad.detach().numpy() !=\n",
    "              0), \"loss must be differentiable w.r.t. network weights\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Playing the game"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "opt = torch.optim.Adam(network.parameters(), lr=1e-4)\n",
    "epsilon = 0.5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def generate_session(t_max=1000, epsilon=0, train=False):\n",
    "    \"\"\"play env with approximate q-learning agent and train it at the same time\"\"\"\n",
    "    total_reward = 0\n",
    "    s = env.reset()\n",
    "\n",
    "    for t in range(t_max):\n",
    "        a = get_action(s, epsilon=epsilon)\n",
    "        next_s, r, done, _ = env.step(a)\n",
    "\n",
    "        if train:\n",
    "            opt.zero_grad()\n",
    "            compute_td_loss([s], [a], [r], [next_s], [done]).backward()\n",
    "            opt.step()\n",
    "\n",
    "        total_reward += r\n",
    "        s = next_s\n",
    "        if done:\n",
    "            break\n",
    "\n",
    "    return total_reward"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(1000):\n",
    "    session_rewards = [generate_session(\n",
    "        epsilon=epsilon, train=True) for _ in range(100)]\n",
    "    print(\"epoch #{}\\tmean reward = {:.3f}\\tepsilon = {:.3f}\".format(\n",
    "        i, np.mean(session_rewards), epsilon))\n",
    "\n",
    "    epsilon *= 0.99\n",
    "    assert epsilon >= 1e-4, \"Make sure epsilon is always nonzero during training\"\n",
    "\n",
    "    if np.mean(session_rewards) > 300:\n",
    "        print(\"You Win!\")\n",
    "        break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### How to interpret results\n",
    "\n",
    "\n",
    "Welcome to the f.. world of deep f...n reinforcement learning. Don't expect agent's reward to smoothly go up. Hope for it to go increase eventually. If it deems you worthy.\n",
    "\n",
    "Seriously though,\n",
    "* __ mean reward__ is the average reward per game. For a correct implementation it may stay low for some 10 epochs, then start growing while oscilating insanely and converges by ~50-100 steps depending on the network architecture. \n",
    "* If it never reaches target score by the end of for loop, try increasing the number of hidden neurons or look at the epsilon.\n",
    "* __ epsilon__ - agent's willingness to explore. If you see that agent's already at < 0.01 epsilon before it's is at least 200, just reset it back to 0.1 - 0.5."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Record videos\n",
    "\n",
    "As usual, we now use `gym.wrappers.Monitor` to record a video of our agent playing the game. Unlike our previous attempts with state binarization, this time we expect our agent to act ~~(or fail)~~ more smoothly since there's no more binarization error at play.\n",
    "\n",
    "As you already did with tabular q-learning, we set epsilon=0 for final evaluation to prevent agent from exploring himself to death."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# record sessions\n",
    "import gym.wrappers\n",
    "env = gym.wrappers.Monitor(gym.make(\"CartPole-v0\"),\n",
    "                           directory=\"videos\", force=True)\n",
    "sessions = [generate_session(epsilon=0, train=False) for _ in range(100)]\n",
    "env.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# show video\n",
    "from IPython.display import HTML\n",
    "import os\n",
    "\n",
    "video_names = list(\n",
    "    filter(lambda s: s.endswith(\".mp4\"), os.listdir(\"./videos/\")))\n",
    "\n",
    "HTML(\"\"\"\n",
    "<video width=\"640\" height=\"480\" controls>\n",
    "  <source src=\"{}\" type=\"video/mp4\">\n",
    "</video>\n",
    "\"\"\".format(\"./videos/\"+video_names[-1]))  # this may or may not be _last_ video. Try other indices"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
